package com.house.keeper.shiro.util;

import com.house.keeper.entity.User;
import com.house.keeper.shiro.service.MyShiroRealm;
import com.house.keeper.util.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;


/**
 * shiro 工具类
 *	
 * @author zjj
 * @date 2022-05-07
 */
public class ShiroUtils {

    private ShiroUtils(){}
    
    /**
     * 获取shiro subject
     * @return 获取shiro subject
     */
    private static Subject getSubject(){
        return SecurityUtils.getSubject();
    }
    
    /**
     * 获取登录session
     * @return 登录session
     */
    public static Session getSession(){
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 退出登录
     */
    public static void logout(){
        getSubject().logout();
    }
    
    /**
     * 获取登录用户model
     * @return 登录用户model
     */
    public static User getUser(){
    	User user = null;
        Object obj = getSubject().getPrincipal();
        if (obj!=null){
            user = new User();
            BeanUtils.copyBeanProp(user, obj);
        }
        return user;
    }
    
    /**
     * set用户
     * @param user 用户
     */
    public static void setUser(User user){
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }
    
    /**
     * 清除授权信息
     */
    public static void clearCachedAuthorizationInfo(){
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
        realm.clearCacheAuthorizationInfo();
    }
    
    /**
     * 获取登录用户id
     * @return 登录用户id
     */
    public static Integer getUserId(){
        User tUser = getUser();
        if (tUser == null || tUser.getId() == null){
            throw new RuntimeException("用户不存在！");
        }
        return tUser.getId();
    }

    /**
     * 获取登录用户name
     * @return 登录用户name
     */
    public static String getLoginName()
    {
        User tUser = getUser();
        if (tUser == null){
            throw new RuntimeException("用户不存在！");
        }
        return tUser.getUserName();
    }
    
    /**
     * 获取登录用户ip
     * @return 登录用户ip
     */
    public static String getIp(){
        return getSubject().getSession().getHost();
    }
    
    /**
     * 获取登录用户sessionId
     * @return 登录用户sessionId
     */
    public static String getSessionId(){
        return String.valueOf(getSubject().getSession().getId());
    }
}
